package com.trailer.base.net

import com.trailer.base.utils.MMKVManager
import okhttp3.Cookie
import okhttp3.CookieJar
import okhttp3.HttpUrl
import java.util.*

class BCookieJar : CookieJar {
    override fun saveFromResponse(httpUrl: HttpUrl, list: List<Cookie>) {
        //保存cookie
        val cookieStrList = HashSet<String>()
        for (cookie in list) {
            cookieStrList.add(cookie.toString())
        }
        MMKVManager.instance().encode("cookie", cookieStrList)
    }

    override fun loadForRequest(httpUrl: HttpUrl): List<Cookie> {
        //读取cookie
        val cookies: MutableList<Cookie> = ArrayList()
        val cookieStrSet = MMKVManager.instance().decodeStringSet("cookie")
        if (cookieStrSet != null) {
            for (cookieStr in cookieStrSet) {
                val cookie = Cookie.parse(httpUrl, cookieStr)
                cookies.add(cookie!!)
            }
        }
        val domain = httpUrl.topPrivateDomain()
        if (domain != null) {
            val cookie = Cookie.Builder()
                    .domain(domain)
                    .name("XDEBUG_SESSION")
                    .expiresAt(1000)
                    .value("PHPSTORM").build()
            cookies.add(cookie)
        }
        return cookies
    }
}
